import { Component, OnInit, Injector, Output, EventEmitter, Input } from '@angular/core';
import { Service } from '../../../server/server';
import { CudTableService } from '../../../public/serve/cud-table/cud-table.service';
import { HintsService } from '../../../public/serve/hints/hints.service';
import { RemoveTableService } from '../../../public/serve/remove-table/remove-table.service';
import { InitService } from '../../../public/serve/init/init.service';
import { home } from '../../home.data';
import { BaseTreeComponent } from '../../../public/components/base-tree/base-tree.component';
import { HttpClient } from '@angular/common/http';
import { TreeNode } from '../../../public/common/api';

@Component({
  selector: 'app-home-page-table',
  templateUrl: './home-page-table.component.html'
})
export class HomePageTableComponent implements OnInit {

  total: number = 0;
  naturalNum: number = 0;
  totalRecords: number;
  public totalItems: number;
  changeCheck: any = 1;

  isSelectAll: boolean = false;
  isChose: boolean = false;

  homeTabVal: Array<object>;

  files: TreeNode[];

  homeUrl = this.server.baseUrl+"Service/Task/getAllTasksList";

  constructor(
    private server: Service,
    public request: CudTableService,
    private tableListService: CudTableService,
    private hintsService: HintsService,
    private removeTableService: RemoveTableService,
    public initService: InitService,
  ) { }

  ngOnInit() {
    this._homeTabList();
  }

   /**
   * 查询主题词列表
   */
  _homeTabList() {
    let data = this._tableData();
    this.request.postRequest(this.homeUrl, data).then((res: any) => {
      if (res.result_code === '0000') {
        this.homeTabVal = res.result;
        this.files = this._processTreeData(this.homeTabVal, 'taskId', 'parentId', 'name');
        this.totalRecords = res.length;
        this.total = res.length;
      } else {
        this.hintsService.messages(res.message, res.result_code);
      }

      home.pagination.pageNo = 1;
      home.pagination.pageSize = 20;

      this._cancelChecked();
      return;
    })
      .catch((err: any) => {
        this.hintsService.messages("error", "error");
        this._cancelChecked();
        return;
      });
  }

  onNodeExpand(event) {
    const node = event.node;
    let queryData = {
      token: home.retrieval.token,
      //checkStatus   : this.tabCheckStatus,
      //themeTableId: home.retrieval.themeTableId,
      pageNo: 1,
      pageSize: 9999,
      parentId: node.taskId
    };
    this.getChildrenList(queryData, node);
  }

  /**
   * 点击图标显示子级的主题词
   * @param queryData 
   * @param node 
   */
  public getChildrenList(queryData, node) {
    this.request.postRequest(this.homeUrl, queryData).then((data: any) => {

      if (data.result_code == '0000') {
        node['children'] = this._toTree(data.result, node['taskId'], 'taskId', 'parentId', 'name');
        this.files = [...this.files];
        return false;
      } else {
        this.hintsService.messages(data.message, data.result_code);
      }

    }).catch();
  }

  _processTreeData(list: Array<any>, idName, parentIdName, labelName): Array<any> {
    return this._toTree(list, '0', idName, parentIdName, labelName);
  }

  _toTree(list: Array<any>, topId = '0', idName, parentIdName, labelName) {
    let idKey = idName;
    let result = [];
    for (let item of list) {
      if (item[parentIdName] == topId) {

        let children = {};
        let expandedIcon = 'fa fa-folder-open';
        let collapsedIcon = 'fa fa-folder';
        let leaf = false;

        if (item['child'] == '0') {
          expandedIcon = '';
          collapsedIcon = '';
          leaf = true;
        }

        let dataArr = {
          'data': {
            label: item['name'],
            data: item['taskId'],
            expandedIcon: expandedIcon,
            collapsedIcon: collapsedIcon,

            arrchildid: item['arrchildid'],
            arrparentId: item['arrparentId'],
            assignDate: item['assignDate'],
            completeDate:item['completeDate'],
            createBy: item['createBy'],
            child: item['child'],
            name: item['name'],
            createTime: item['createTime'],
            completeStatus: item['completeStatus'],
            idxTaskThemeTableList: item['idxTaskThemeTableList'],
            taskAssignList: item['taskAssignList'],
            submitStatus: item['submitStatus'],
            subCount: item['subCount'],
            taskId: item['taskId'],
            parentId: item['parentId'],
            mainCompleteStatus:item['mainCompleteStatus'],
            checkCompleteDate:item['checkCompleteDate'],
            listorder:item['mainCompleteStatus'],
            siteId:item['siteId'],
            productCount:item['productCount'],
            taskCheckBy:item['taskCheckBy'],
            taskStatus:item['taskStatus'],
            description: item['description'],
            taskType:item['taskType'],
            completeCount:item['completeCount'],
            checkStatus:item['checkStatus'],
            checkCount:item['checkCount'],
            labelId: item['labelId'],
            labelName: item['labelName'],
          },
          'leaf': leaf,
          'taskId': item['taskId']
        };

        result.push(dataArr);
      }
    }
    return result;
  }

   /**
   * 重置表格复选框、选中的ID
   */
  private _cancelChecked() {
    this.isChose = this.isSelectAll = false;
    this.removeTableService._clearId("taskId");
  }


  //查询参数
  private _tableData() {
    return {
      token: home.retrieval.token,
      pageNo: home.pagination.pageNo,
      pageSize: home.pagination.pageSize,
      parentId: home.retrieval.parentId,
      createBy: this.server.getuserName(),
      queryCriteria:home.retrieval.queryCriteria,
      taskType: home.retrieval.taskType,
      completeStatus:home.retrieval.completeStatus
    }
  }


}
